package com.onpositive.data.serializer.readers;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.BitSet;
import java.util.LinkedHashSet;

import com.onpositive.data.AbstractReader;
import com.onpositive.data.serializer.writers.AbstractWriter;

public  class RemoteByteArrayReader extends AbstractReader<Object>{

	public abstract static class Downloader{
		
		public abstract byte[] getContent(int i);
	}

	private Downloader loader;
	
	public RemoteByteArrayReader(Class<Object> clazz,File cache,Downloader loader) {
		super(clazz);
		this.fl=cache;
		this.loader=loader;
	}
	@Override
	public void setValue(int num, Object value) {
		throw new UnsupportedOperationException();
	}
	
	File fl;

	@Override
	public Object getObject(int i) {
		if (fl==null){
			return download(i);
		}
		File file2 = new File(fl,i+".cache");
		if (!file2.exists()){
			return download(i);
		}
		if (file2.exists()){
			long length = file2.length();
			byte[] mm=new byte[(int) length];
			try {
				DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file2));
				dataInputStream.readFully(mm);
				return mm;
			} catch (IOException e) {
				throw new IllegalStateException(e);
			}
		}
		return null;
	}

	protected byte[] download(int i) {
		byte[] content = loader.getContent(i);
		File file2 = new File(fl,i+".cache");
		if (content==null){
			return content;
		}
		try{
		FileOutputStream dd=new FileOutputStream(file2);
		dd.write(content);
		dd.close();
		}catch (Exception e) {
			return content;
		}
		return content;
	}

	@Override
	protected void doInit() {
		
	}

	@Override
	public void filterOut(LinkedHashSet<Object> obj, String text) {
		
	}


	@Override
	public boolean accept(int op, int a, Object constraint) {
		return false;
	}

	@Override
	public Object aggregate(int op, BitSet ss) {
		return null;
	}
	@Override
	public AbstractWriter<Object> getWriter() {
		throw new UnsupportedOperationException();
	}
	@Override
	public void initEmpty(int dataSize) {
		
	}
	@Override
	public void expand(int newSize) {
		
	}

}
